import { deepMix } from '@antv/util';
import { quadratic, labelCfg } from '@/graph/style/edge-style';

export default (G6) => {
  G6.registerEdge('quadratic-edge', {

    shouldBegin() {
      return true;
    },

    setState(name, value, item) {
      const group = item.getContainer();
      const shape = group.get('children')[0];

      if (name !== 'running') return;
      if (value) {
        return this.nextRrunning(item.getModel(), group);
      }
      shape.stopAnimate();

    },

    draw(cfg, group) {
      const keyShape = group.addShape('path', { name: 'edge-shape', attrs: deepMix({}, this.getShapeStyle(cfg), quadratic, cfg.style) });

      cfg.animate && this.running(cfg, group);
      this.setLabel(cfg, group);
      return keyShape;

    },

    setLabel(cfg, group) {
      const path = group.get('children')[0];
      group.addShape('text', {
        name: 'edge-label',
        attrs: deepMix(this.getLabelStyle(cfg, group), path.getPoint(0.5), { text: cfg.label, }, labelCfg)
      });
    },

    running(cfg, group) {
      const shape = group.get('children')[0];

      const length = shape.getTotalLength();

      function fn(ratio) {
        const startLen = ratio * length;

        return { lineDash: [startLen, length - startLen] };
      }
      function callback() {
        shape.attr('lineDash', cfg.style.lineDash);
        this.nextRrunning(cfg, group);
      }
      shape.animate(fn, { repeat: false, duration: 2000, callback: callback.bind(this) });
    },

    nextRrunning(cfg, group) {
      let index = 0;
      const shape = group.get('children')[0];
      const { lineDash, stroke, lineAppendWidth, lineWidth } = shape.get('attrs');
      function fn() {
        index++;
        if (index > 9) index = 0;
        return {
          lineDashOffset: -index,
          lineDash,
          stroke,
          lineAppendWidth,
          lineWidth,
        };
      }
      shape.animate(fn, { repeat: 1, duration: 3000 },);
    },

    update: undefined,

  }, "quadratic");
}